<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false" :before-close="close">
      <el-form ref="RefForm" :model="formData" label-width="160px" :validate-on-rule-change="false" :rules="formRules" status-icon>
        <el-form-item v-if="!isForChild" label="上级部门" prop="roleName">
          <el-input v-model="formData.roleName" maxlength="16" show-word-limit />
        </el-form-item>
        <el-form-item v-if="isForChild" label="上级部门">
          <span>{{ formData.parentName }}</span>
        </el-form-item>
        <el-form-item v-if="isForChild" label="部门名称" prop="roleName">
          <el-input v-model="formData.roleName" maxlength="16" show-word-limit />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="formData.remarks" maxlength="16" show-word-limit />
        </el-form-item>
        <el-form-item label="Logo图" prop="remarks">
          <div>
            <img v-if="formData.logo && formData.logo !== ''" class="logoimage" :src="imageBase + formData.logo" />
            <el-button v-if="formData.logo && formData.logo !== ''" size="mini" class="deleteLogo" type="text" @click="deleteLogo">删除</el-button></el-button>
          </div>
          <el-upload
            ref="imgRef"
            class="upload-demo"
            :headers="{
              Authorization: `Bearer ${$store.getters.token}`
            }"
            :action="httpUrl"
            multiple
            :limit="1"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="false"
          >
            <el-button size="mini" type="primary">选择</el-button>
          </el-upload>
          <span style="color: #999; margin-left: 10px">(图片只能是 JPG 格式,建议宽高：40px * 40px)</span>
        </el-form-item>
        <el-form-item label="可用菜单列表">
          <el-tree
            ref="tree"
            empty-text="加载中..."
            :data="treeData"
            show-checkbox
            node-key="id"
            :check-strictly="false"
            :default-expand-all="true"
            :default-checked-keys="arr"
            :props="defaultProps"
            :check-on-click-node="true"
            @check-change="change"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span :class="data.isVisable ? '' : 'invisable'">{{ data.name }}</span>
            </span>
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loadingSubmit" type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Role, RoleDetail } from '@/api/Role' // RoleSearch
// import { HostUser, HostUserDetail } from '@/api/HostUser'
import { eleValidator } from '@/utils/tools'
import { MenuAll, MenuAll2 } from '@/api/Menu'
export default {
  data() {
    return {
      httpUrl: `${process.env.VUE_APP_BASE_API}Common/Upload`,
      imageBase: process.env.VUE_APP_BASE_API,
      isForChild: false,
      treeData: [],
      defaultProps: {
        children: 'childMenus',
        label: 'name'
      },
      arr: [],
      id: '',
      title: '',
      isEdit: false,
      loadingSubmit: false,
      dialogVisible: false,
      formData: {
        logo: '',
        roleName: '',
        remarks: '',
        parentName: '',
        parentId: 0,
        reloadParentId: 0
      },
      formRules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            validator: eleValidator([
              { rule: 'isEmpty', msg: '名称不能为空' },
              {
                rule: 'isRepeat',
                msg: {
                  value: '名称重复，名称必须全系统唯一，请更换',
                  url: '/Role/Exists',
                  key: 'roleName'
                }
              }
            ]),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    checkedRole(newVal) {
      if (newVal.length === this.roleList.length) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    }
  },
  methods: {
    deleteLogo() {
      this.formData.logo = ''
    },
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.formData.logo = res.data.url
      }
      this.$refs.imgRef.clearFiles()
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
      return isJPG
    },
    async getMenuList(parentId) {
      if (parentId === 0) {
        parentId = 1
      }
      const { data } = await MenuAll({ pageIndex: 1, pageSize: 10, menuId: parentId })
      this.treeData = data
    },
    async getMenuList2(parentId, ids) {
      if (parentId === 0) {
        parentId = 1
      }
      const { data } = await MenuAll2({ pageIndex: 1, pageSize: 10, menuId: ids.join(',') })
      this.treeData = data
    },
    async open(row, isChild, isEdit) {
      this.formData.logo = row.logo
      this.isForChild = isChild
      var id = row.id
      this.dialogVisible = true
      this.formData.parentId = 0
      if (isChild) {
        this.formData.parentName = row.roleName
        this.formData.parentId = row.id
        if (row.hasChildren) {
          this.formData.reloadParentId = row.id
        } else {
          this.formData.reloadParentId = row.parentId
        }
      }

      if (isEdit) {
        this.formData.reloadParentId = row.parentId
        this.formData.parentName = row.parentName
        this.formData.parentId = row.parentId
        this.title = isChild ? '编辑部门' : '编辑建设单位'
        this.id = id
        this.isEdit = true
        const { data } = await RoleDetail({ id })
        this.formData.roleName = data.roleName
        this.formData.remarks = data.remarks

        const allMenusIds = data.menuRoles.map((r) => r.menu).map((r) => r.parentId)
        console.info('allMenus', allMenusIds)
        const filterMenus = data.menuRoles.filter((item) => {
          return allMenusIds.indexOf(item.menuId) < 0
        })
        console.info('filterMenus', filterMenus)
        this.arr = filterMenus.map((r) => r.menuId)
        console.info('arr', this.arr)
      } else {
        this.$nextTick(function () {
          this.$refs.RefForm.resetFields()
          this.$refs.tree.setCheckedKeys([])
        })
        this.title = isChild ? '新增部门' : '新增建设单位'
      }
    },
    change() {},
    handleSubmit() {
      this.loadingSubmit = true
      this.$refs.RefForm.validate(async (valid) => {
        if (valid) {
          let method = ''
          let obj = {}
          if (this.isEdit) {
            method = 'PUT'
            obj = {
              id: this.id,
              value: {
                parentId: this.formData.parentId,
                roleName: this.formData.roleName,
                remarks: this.formData.remarks,
                logo: this.formData.logo,
                menuRoles: this.$refs.tree.getCheckedNodes(false, false).map((item) => {
                  return { menuId: item.id }
                })
              }
            }
          } else {
            method = 'POST'
            obj = {
              parentId: this.formData.parentId,
              roleName: this.formData.roleName,
              remarks: this.formData.remarks,
              logo: this.formData.logo,
              menuRoles: this.$refs.tree.getCheckedNodes(false, false).map((item) => {
                return { menuId: item.id }
              })
            }
          }
          Role(method, obj)
            .then((res) => {
              if (res.data.success) {
                this.cancel()
                this.$emit('reloadParent', this.formData.reloadParentId)
                this.$emit('getList')
                this.$message.success('保存成功！')
              }
            })
            .catch((err) => {
              console.log(err)
              this.loadingSubmit = false
              this.$message.error('保存失败！')
            })
        } else {
          this.loadingSubmit = false
        }
      })
    },
    // 单选
    handlecheckedRoleChange() {},
    close() {
      this.isEdit = false
      this.loadingSubmit = false
      this.dialogVisible = false
      this.formData.roleName = ''
      this.id = ''
      this.treeData = []
      this.ids = []
    },
    cancel() {
      this.close()
    }
  }
}
</script>

<style lang="scss" scoped>
  .deleteLogo {
    margin: 0px 10px;
    color: red;
  }
  .logoimage {
    width: 40px;
    height: 40px;
  }
  .invisable {
    color: #ccc;
  }
  .el-dialog__title {
    color: #999999;
  }
</style>
